//
//  WorkerOnJobViewController.swift
//  mggz
//
//  Created by 匀视网Mac on 2018/2/26.
//  Copyright © 2018年 爱丽丝的梦境. All rights reserved.
//

import UIKit
import Moya
import ObjectMapper
class WorkerOnJobViewController: UIViewController {
    @IBOutlet weak var bottomlayout: UIView!
    
    @IBOutlet weak var tableviewBottom: NSLayoutConstraint!
    @IBOutlet weak var bottomlead: NSLayoutConstraint!
    @IBOutlet weak var tableView: UITableView!
    
    @IBOutlet weak var addProjectBtn: UIView!
    @IBOutlet weak var delPersonBtn: UIView!
    @IBOutlet weak var blackPersonBtn: UIView!
    
    var rightitemBar:UIBarButtonItem?
    
    var isRefresh:Bool?{
        get{
            return false
        }
        set(newValue){
            if newValue!{
                self.clearSelectData()
                self.setupOtherWNGData()
                self.showOrhideLayout()
            }
        }
    }
    
    lazy var delDialog:CustomDialog = {
        var dialog = CustomDialog(frame: CGRect.zero, _title: "提示", _status: "确定要删除这些民工吗？删除之后将会丢失他们的个人资料", _submitclick: {
            self.delDialog.dismiss()
            self.delOperate()
        })
        return dialog
    }()
    lazy var blackDialog:CustomDialog = {
        var dialog = CustomDialog(frame: CGRect.zero, _title: "提示", _status: "确定要拉黑这些民工吗？", _submitclick: {
            self.blackDialog.dismiss()
            self.addBlackPerson()
        })
        return dialog
    }()
    
    
    lazy var itemArray : [WNGCompanyMembersModel] = [WNGCompanyMembersModel]()
    var markArray:NSMutableArray?
    var isShow = false
    lazy var membersSelectArray : [String] = [String]()
    /*var currentProject: LCProjectListModel? {
        willSet {
            self.currentProject = newValue
        }
    }*/
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        WWProgressHUD.dismiss()
    }
    
    func addClick(_ view:UIView){
        var t = UITapGestureRecognizer(target: self, action: #selector(selectClick(_:)))
        t.numberOfTapsRequired = 1
        t.numberOfTouchesRequired = 1
        t.delegate = self
        view.addGestureRecognizer(t)
    }
    
    @objc func selectClick(_ sender:UIGestureRecognizer){
        
        if self.membersSelectArray.count == 0{
            QWTextonlyHud("请先选择人员", target: self.view)
            return
        }
        
        
        
        print("\(sender.view?.tag)")
        if sender.view?.tag == 0{
            var projectvc = ProjectListControllerViewController(nibName: "ProjectListControllerViewController", bundle: nil)
            projectvc.selectarray.append(contentsOf: self.membersSelectArray)
            self.navigationController?.pushViewController(projectvc, animated: true)
            
        }else if sender.view?.tag == 1{
            self.delDialog.show()
        }else if sender.view?.tag == 2{
            
            self.blackDialog.show()
        }
    }
    
    func delOperate(){
        if self.membersSelectArray.count > 0{
            QWTextWithStatusHud("正在加载中...", target: self.view)
            //WWProgressHUD.showWithStatus("正在加载中...")
            var params:[String:Any] = ["isSingle":"false","migrantWorkerIDList":self.membersSelectArray]
            MNetHttp.sharedInstance.postSingle(API_CALL_METHOD, method: .DELEPERSON, params: &params, type: DelPerson.self, success: { (bean,_) in
                //WWProgressHUD.inform("操作成功")
                QWHudDiss(self.view)
                QWTextonlyHud("操作成功", target: self.view)
                self.clearSelectData()
                self.setupOtherWNGData()
                self.showOrhideLayout()
                
            }) { (error) in
                QWHudDiss(self.view)
                switch error{
                case .DATAERROR:
                    QWTextonlyHud("数据异常", target: self.view)
                    break
                case .HTTPERROR:
                    QWTextonlyHud("网络异常", target: self.view)
                case .DATAFAIL:
                    QWTextonlyHud("数据异常", target: self.view)
                case .StateFail(let data):
                    guard let t = data as? String else{
                        QWTextonlyHud("数据异常", target: self.view)
                        return
                    }
                    QWTextonlyHud(t, target: self.view)
                }
                //WWProgressHUD.error("数据异常")
            }
        }else{
            QWTextonlyHud("请先选择人员", target: self.view)
        }
        
    }
    
    func addBlackPerson(){
        if self.membersSelectArray.count > 0{
            QWTextWithStatusHud("正在加载中...", target: self.view)
            var params:[String:Any] = ["isSingle":"true","migrantWorkerIDList":self.membersSelectArray]
            MNetHttp.sharedInstance.postSingle(API_CALL_METHOD, method: .ADDBLACKPERSON, params: &params, type: DelPerson.self, success: { (bean,_) in
                
                QWHudDiss(self.view)
                QWTextonlyHud("操作成功", target: self.view)
                self.clearSelectData()
                self.setupOtherWNGData()
                self.showOrhideLayout()
                
            }) { (error) in
                QWHudDiss(self.view)
                switch error{
                case .DATAERROR:
                    QWTextonlyHud("数据异常", target: self.view)
                    break
                case .DATAFAIL:
                    QWTextonlyHud("数据异常", target: self.view)
                    break
                case .HTTPERROR:
                    QWTextonlyHud("网络异常", target: self.view)
                    break
                case .StateFail(let data):
                    guard let dic = data as? Dictionary<String,Any> else{
                        
                        guard let str = data as? String else{
                            QWTextonlyHud("数据异常", target: self.view)
                            return
                        }
                        QWTextonlyHud("\(str)", target: self.view)
                        return
                    }
                    QWTextonlyHud(dic["Msg"] as? String, target: self.view)
                    break
                }
                
            }
        }else{
            QWTextonlyHud("请先选择人员", target: self.view)
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.bottomlead.constant = -80
        self.navigationItem.title = "在职民工"
        self.rightitemBar = UIBarButtonItem()
        self.rightitemBar?.title = "多选"
        self.rightitemBar?.target = self
        self.rightitemBar?.action = #selector(rightItemClick)//UIBarButtonItem(title: "多选", fontSize: 17, self, #selector(rightItemClick))
        self.navigationItem.rightBarButtonItem = self.rightitemBar
        self.setupOtherWNGData()
        self.tableView.delegate = self
        self.tableView.dataSource = self
        self.tableView.separatorInset = UIEdgeInsetsMake(0, 10, 0, 10)
        self.tableView.separatorInset = UIEdgeInsets.zero
        self.tableView.separatorStyle = .singleLine
        self.tableView.separatorColor = UIColor.init(red: 233/255.0, green: 233/255.0, blue: 233/255.0, alpha: 1)
        self.tableView.backgroundColor = UIColor.init(red: 233/255.0, green: 233/255.0, blue: 233/255.0, alpha: 1)
        view.backgroundColor = UIColor.init(red: 233/255.0, green: 233/255.0, blue: 233/255.0, alpha: 1)
        self.tableView.register(UINib.init(nibName: "WNGOtherCell", bundle: nil), forCellReuseIdentifier: "other")
        
        self.view.bringSubview(toFront: self.tableView)
        
        self.addClick(self.addProjectBtn)
        self.addClick(self.delPersonBtn)
        self.addClick(self.blackPersonBtn)
    }
    @objc fileprivate func rightItemClick(){
        /*guard let accountId = WWUser.sharedInstance.accountId else{
            return
        }
        guard self.membersSelectArray.count>0 else {
            WWProgressHUD.error("未选中目标")
            return
        }
        WWProgressHUD.showWithStatus("正在加入中...")*/
        /*LCAPiMainManager.request(.mwJoinTheProject(SupplyBaseId: (currentProject?.MarketSupplyBaseID)!, DataItemList: self.membersSelectArray as NSArray, AccountId: accountId)) { (result) in
            if case let .success(response) = result {
                guard  let jsonString :NSDictionary = try?response.mapJSON() as! NSDictionary else{
                    return
                }
                guard (jsonString["State"]) as! String == "OK" else{
                    return
                }
                WWProgressHUD.dismiss()
                self.navigationController?.popViewController(animated: true)
                //  self.guid = (jsonString["Guid"] as! String)
            }
        }*/
        
        
        self.clearSelectData()
        self.showOrhideLayout()
        self.tableView.reloadData()
    }
    
    func clearSelectData(){
        for (p,item) in self.markArray!.enumerated(){
            if (item as? String) == "1"{
                self.markArray?.replaceObject(at: p, with: "0")
            }
        }
        self.membersSelectArray.removeAll()
    }
    
    func showOrhideLayout(){
        self.isShow = self.isShow ? false:true
        
        if self.isShow {
            self.rightitemBar?.title = "取消"
            self.view.bringSubview(toFront: self.bottomlayout)
        }else{
            self.rightitemBar?.title = "多选"
            self.view.bringSubview(toFront: self.tableView)
        }
        if self.isShow {
            self.bottomlead.constant = 0
            UIView.animate(withDuration: 0.3, animations: {
                self.view.layoutIfNeeded()
            }, completion: { (flag) in
                if flag{
                    self.tableviewBottom.constant = 80
                    self.view.layoutIfNeeded()
                }
            })
        }else{
            self.bottomlead.constant = -80
            self.tableviewBottom.constant = 0
            UIView.animate(withDuration: 0.3) {
                
                
                self.view.layoutIfNeeded()
            }
        }
        
    }
    
    
    
    func setupOtherWNGData(){
        guard let accountId = WWUser.sharedInstance.accountId else{
            return
        }
        /*guard ((currentProject?.MarketSupplyBaseID) != nil) else {
            return
        }*/
        QWTextWithStatusHud("正在加载中...", target: self.view)
        LCAPiMainManager.request(.GetOnlineWorkerOfCompany(pageIndex: 1, pageSize: 200, AccountId: accountId, marketSupplyBaseID: "")) { (result) in
            QWHudDiss(self.view)
            if case let .success(response) = result {
                guard  let jsonString :NSDictionary = try?response.mapJSON() as! NSDictionary else{
                    
                    return
                }
                guard (jsonString["State"]) as! String == "OK" else{
                    return
                }
                guard let resultDic = jsonString["Result"] as? [String: AnyObject] else{
                    return
                }
                guard let itemsArr = resultDic["Items"] as? [[String: Any]] else{
                    return
                }
                self.itemArray = Mapper<WNGCompanyMembersModel>().mapArray(JSONArray: itemsArr)
                self.markArray = NSMutableArray()
                for _ in 0..<self.itemArray.count{
                    self.markArray?.add("0")
                }
                self.tableView.reloadData()
                
            }
        }
    }

}

extension WorkerOnJobViewController:UIGestureRecognizerDelegate{
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
        if touch.view is UITableView{
            return false
        }else{
            return true
        }
        
    }
}

extension WorkerOnJobViewController:UITableViewDelegate,UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.itemArray.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell : WNGOtherCell = tableView.dequeueReusableCell(withIdentifier: "other") as! WNGOtherCell
        cell.setupCompanyOnJobWorkerDataWithModel(self.itemArray[indexPath.row])
        let markStr : String = (self.markArray?[indexPath.row] as? String) ?? "0"
        if markStr == "0" {
            cell.coverView.isHidden = true
        }else if markStr == "1" {
            cell.coverView.isHidden = false
        }
        return cell
    }
    func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
        
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        let selectModel : WNGCompanyMembersModel = self.itemArray[indexPath.row]
        if isShow{
            /*if selectModel.OnWorking ?? false {
                
            }else{*/
                let markStr : String = self.markArray![indexPath.row] as! String
                if markStr == "0"{
                    self.markArray?.replaceObject(at: indexPath.row, with: "1")
                    self.membersSelectArray.append(selectModel.MigrantWorkerID!)
                }else if markStr == "1"{
                    self.markArray?.replaceObject(at: indexPath.row, with: "0")
                    for (index,value) in self.membersSelectArray.enumerated(){
                        if value == selectModel.MigrantWorkerID{
                            self.membersSelectArray.remove(at: index)
                        }
                    }
                }
                self.tableView.reloadData()
            //}
            
        }else{
            let mwDetail = MWDetailInfoViewController(nibName: "MWDetailInfoViewController", bundle: nil)
            mwDetail.reFreshData = {(value) in
                if value == true {
                    //self.setupOtherWNGData()
                }
            }
            mwDetail.isDefault = (selectModel.OnWorking ?? false) ?.nocurrent:.noone
            mwDetail.MigrantWorkerID = selectModel.MigrantWorkerID
            mwDetail.currentProjectName = ProjectName
            mwDetail.currentProjectId = ProjectId
            mwDetail.isZG = false
            mwDetail.LocateTime = ""//"2018-12-12"
            //mwDetail.currentProject = selectedProject
            self.navigationController?.pushViewController(mwDetail, animated: true)
            
        }
        
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 70
    }
}
